<template>
   <el-dialog
      title="查看权限"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
   >
      <div class="assign-permission-container">
         <div class="permission-tree-container">
            <!-- 左侧菜单部分 -->
            <div class="left-menu">
               <div class="menu-tree">
                  <div
                     v-for="group in filteredGroups"
                     :key="group.group_name"
                     class="menu-item"
                     :class="{ active: activeGroupName === group.group_name }"
                     @click="activeGroupName = group.group_name"
                  >
                     <div class="menu-item-header">
                        <el-checkbox
                           :model-value="isGroupChecked(group.list)"
                           :indeterminate="isGroupIndeterminate(group.list)"
                           @change="(val) => handleGroupCheck(val, group)"
                        ></el-checkbox>
                        <span>{{ group.group_name }}</span>
                        <span
                           v-if="getGroupCheckedCount(group.list) > 0"
                           class="checked-count"
                           >({{ getGroupCheckedCount(group.list) }})</span
                        >
                     </div>

                     <div class="sub-menu-list">
                        <div
                           v-for="parentGroup in getParentGroups(group.list)"
                           :key="parentGroup.parent_name"
                           class="sub-menu-item"
                        >
                           <el-checkbox
                              v-model="parentGroup.checked"
                              :indeterminate="parentGroup.indeterminate"
                              @change="(val) => handleParentCheck(val, parentGroup.items)"
                           ></el-checkbox>
                           <span>{{ parentGroup.parent_name }}</span>
                           <span
                              v-if="getCheckedCount(parentGroup.items) > 0"
                              class="checked-count"
                              >({{ getCheckedCount(parentGroup.items) }})</span
                           >
                        </div>
                     </div>
                  </div>
               </div>
            </div>

            <!-- 右侧详细权限部分 -->
            <div class="right-permission-detail">
               <div
                  v-if="currentGroup"
                  class="permission-section"
               >
                  <div class="section-header">
                     <el-checkbox
                        :model-value="isGroupChecked(currentGroup.list)"
                        :indeterminate="isGroupIndeterminate(currentGroup.list)"
                        @change="(val) => handleGroupCheck(val, currentGroup)"
                     ></el-checkbox>
                     <span>{{ currentGroup.group_name }}</span>
                  </div>

                  <div class="section-content">
                     <div
                        v-for="parentGroup in getParentGroups(currentGroup.list)"
                        :key="parentGroup.parent_name"
                        class="permission-group"
                     >
                        <div class="permission-group-header">
                           <el-checkbox
                              v-model="parentGroup.checked"
                              :indeterminate="parentGroup.indeterminate"
                              @change="(val) => handleParentCheck(val, parentGroup.items)"
                           ></el-checkbox>
                           <span>{{ parentGroup.parent_name }}</span>
                        </div>

                        <div class="permission-items">
                           <div
                              v-for="item in parentGroup.items"
                              :key="item.id"
                              class="permission-item"
                           >
                              <el-checkbox
                                 v-model="item.is_checked"
                                 :true-label="1"
                                 :false-label="0"
                                 @change="() => handlePermissionCheck(item, parentGroup)"
                              ></el-checkbox>
                              <span>{{ item.child_name }}</span>
                              <span
                                 v-if="item.status !== 1"
                                 class="status-disabled"
                                 >(禁用)</span
                              >
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
               <div
                  v-else
                  class="empty-tip"
               >
                  请在左侧选择一个权限分组
               </div>
            </div>
         </div>
      </div>
   </el-dialog>
</template>

<script setup>
   import { ref, defineExpose } from "vue";
   import api from "@/api/index.js";
   import { ElMessage } from "element-plus";
   const dialogVisible = ref(false); // 弹窗是否显示
   const permissionList = ref([]); // 权限列表数据

   const openDialog = (data) => {
      dialogVisible.value = true;
      GetPermissions(data);
      getAllPermissions();
   };
   // 获取用户拥有的权限
   const GetPermissions = async (data) => {
      const res = await api.authority.getUserRouter({ id: data.id });
      console.log(res);
      if (res.code == 0) {
         permissionList.value = res.data.map((item) => ({
            id: item.id,
         }));
         console.log(permissionList.value);
      } else {
         ElMessage.error(res.msg);
      }
   };

   //    --------------------------------------

   // 角色ID
   const roleId = ref(null);

   // 角色数据
   const roleData = ref({});

   // 权限分组数据
   const permissionGroups = ref([]);

   // 搜索
   const searchText = ref("");

   // 当前激活的权限组
   const activeGroupName = ref("");

   // 当前选中的权限组
   const currentGroup = computed(() => {
      return permissionGroups.value.find((g) => g.group_name === activeGroupName.value) || null;
   });

   // 过滤后的权限分组
   const filteredGroups = computed(() => {
      if (!permissionGroups.value || permissionGroups.value.length === 0) {
         return [];
      }

      if (!searchText.value) {
         return permissionGroups.value;
      }

      // 搜索过滤
      const keyword = searchText.value.toLowerCase();
      return permissionGroups.value
         .map((group) => {
            const filteredList = (group.list || []).filter(
               (item) =>
                  item.child_name?.toLowerCase().includes(keyword) ||
                  item.parent_name?.toLowerCase().includes(keyword) ||
                  (item.route_url && item.route_url.toLowerCase().includes(keyword))
            );

            return {
               ...group,
               list: filteredList,
            };
         })
         .filter((group) => group.list.length > 0);
   });

   // 已选权限列表
   const selectedPermissions = computed(() => {
      const result = [];
      permissionGroups.value.forEach((group) => {
         if (group.list && Array.isArray(group.list)) {
            group.list.forEach((permission) => {
               if (permission.is_checked === 1) {
                  result.push({
                     ...permission,
                     group_name: group.group_name,
                  });
               }
            });
         }
      });
      return result;
   });

   // 已选权限数量
   const selectedPermissionsCount = computed(() => {
      return selectedPermissions.value.length;
   });

   // 获取所有权限列表
   const getAllPermissions = async () => {
      try {
         const res = await api.authority.getRoleMenu();

         if (res.code === 0) {
            // 处理返回的数据
            permissionGroups.value = (res.data || []).map((group) => {
               // 确保每个权限项都有is_checked属性
               const processedList = (group.list || []).map((item) => ({
                  ...item,
                  is_checked: Number(item.is_checked || 0),
               }));

               return {
                  ...group,
                  list: processedList,
               };
            });

            // 设置默认激活的分组
            if (permissionGroups.value.length > 0) {
               activeGroupName.value = permissionGroups.value[0].group_name;
            }
            console.log(permissionGroups.value);
         } else {
            ElMessage.error(res.msg || "获取权限列表失败");
         }
      } catch (error) {
         console.error("获取权限列表出错:", error);
         ElMessage.error("获取权限列表出错");
      }
   };

   // 按父级菜单分组
   const getParentGroups = (permissions) => {
      if (!permissions || !Array.isArray(permissions)) {
         return [];
      }

      // 按parent_name分组
      const groups = {};
      permissions.forEach((item) => {
         const parentName = item.parent_name || "其他";
         if (!groups[parentName]) {
            groups[parentName] = {
               parent_name: parentName,
               items: [],
               checked: false,
               indeterminate: false,
            };
         }
         groups[parentName].items.push(item);
      });

      // 计算父级菜单的选中状态
      Object.values(groups).forEach((group) => {
         updateParentCheckedState(group);
      });

      // 转换为数组并排序
      return Object.values(groups).sort((a, b) => {
         const itemA = a.items[0];
         const itemB = b.items[0];
         return (itemA?.show_sort || 0) - (itemB?.show_sort || 0);
      });
   };

   // 更新父级菜单的选中状态
   const updateParentCheckedState = (parentGroup) => {
      const allChecked = parentGroup.items.every((item) => item.is_checked === 1);
      const anyChecked = parentGroup.items.some((item) => item.is_checked === 1);

      parentGroup.checked = allChecked;
      parentGroup.indeterminate = anyChecked && !allChecked;
   };

   // 检查分组是否全选
   const isGroupChecked = (items) => {
      if (!items || !Array.isArray(items) || items.length === 0) return false;
      return items.every((item) => item.is_checked === 1);
   };

   // 检查分组是否部分选中
   const isGroupIndeterminate = (items) => {
      if (!items || !Array.isArray(items) || items.length === 0) return false;
      const anyChecked = items.some((item) => item.is_checked === 1);
      const allChecked = items.every((item) => item.is_checked === 1);
      return anyChecked && !allChecked;
   };

   // 获取已选中数量
   const getCheckedCount = (items) => {
      if (!items || !Array.isArray(items)) return 0;
      return items.filter((item) => item.is_checked === 1).length;
   };

   // 获取分组已选中数量
   const getGroupCheckedCount = (items) => {
      if (!items || !Array.isArray(items)) return 0;
      return items.filter((item) => item.is_checked === 1).length;
   };

   // 处理权限组选中状态变化
   const handleGroupCheck = (checked, group) => {
      if (group.list && Array.isArray(group.list)) {
         group.list.forEach((item) => {
            if (item.status === 1) {
               // 只选择启用状态的权限
               item.is_checked = checked ? 1 : 0;
            }
         });
      }

      // 强制刷新已选列表
      forceRefreshSelectedPermissions();
   };

   // 处理父级菜单选中状态变化
   const handleParentCheck = (checked, items) => {
      if (items && Array.isArray(items)) {
         items.forEach((item) => {
            if (item.status === 1) {
               // 只选择启用状态的权限
               item.is_checked = checked ? 1 : 0;
            }
         });
      }

      // 强制刷新已选列表
      forceRefreshSelectedPermissions();
   };

   // 处理权限勾选状态变化
   const handlePermissionCheck = (permission, parentGroup) => {
      // 更新父级菜单的选中状态
      if (parentGroup) {
         updateParentCheckedState(parentGroup);
      }

      // 确保触发计算
      forceRefreshSelectedPermissions();
   };

   // 强制刷新已选列表
   const forceRefreshSelectedPermissions = () => {
      const temp = [...permissionGroups.value];
      permissionGroups.value = temp;
   };
   defineExpose({
      openDialog,
   });
</script>
<style scoped>
   .el-table {
      margin-bottom: 20px;
   }
   .assign-permission-dialog :deep(.el-dialog__body) {
      padding: 10px 20px;
      max-height: 70vh;
      overflow: hidden;
   }

   .assign-permission-container {
      width: 100%;
      height: 60vh;
      display: flex;
      flex-direction: column;
   }

   .permission-tree-container {
      display: flex;
      flex: 1;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      overflow: hidden;
      height: 100%;
   }

   /* 左侧菜单样式 */
   .left-menu {
      width: 260px;
      border-right: 1px solid #e0e0e0;
      background-color: #f5f7fa;
      height: 100%;
   }

   .search-box {
      padding: 10px;
      border-bottom: 1px solid #e0e0e0;
   }

   .menu-tree {
      padding: 10px 0;
      overflow-y: auto;
      height: calc(100% - 64px);
   }

   .menu-item {
      padding: 0 10px;
   }

   .menu-item.active {
      background-color: #f0f2f5;
   }

   .menu-item-header {
      height: 40px;
      line-height: 40px;
      display: flex;
      align-items: center;
      cursor: pointer;
   }

   .menu-item-header .el-checkbox {
      margin-right: 5px;
   }

   .checked-count {
      margin-left: 5px;
      font-size: 12px;
      color: #f56c6c;
   }

   .sub-menu-list {
      padding-left: 20px;
   }

   .sub-menu-item {
      height: 32px;
      line-height: 32px;
      display: flex;
      align-items: center;
   }

   .sub-menu-item .el-checkbox {
      margin-right: 5px;
   }

   /* 右侧详细权限样式 */
   .right-permission-detail {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      height: 100%;
   }

   .permission-section {
      margin-bottom: 20px;
   }

   .section-header {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
   }

   .section-header .el-checkbox {
      margin-right: 5px;
   }

   .section-content {
      padding-left: 20px;
   }

   .permission-group {
      margin-bottom: 15px;
   }

   .permission-group-header {
      font-weight: bold;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
   }

   .permission-group-header .el-checkbox {
      margin-right: 5px;
   }

   .permission-items {
      display: flex;
      flex-wrap: wrap;
      padding-left: 20px;
   }

   .permission-item {
      width: 20%;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
   }

   .permission-item .el-checkbox {
      margin-right: 5px;
   }

   .status-disabled {
      margin-left: 5px;
      font-size: 12px;
      color: #c0c4cc;
   }

   .empty-tip {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #909399;
      font-size: 14px;
   }

   /* 底部按钮样式 */
   .dialog-footer {
      display: flex;
      justify-content: center;
      gap: 20px;
   }

   .dialog-footer .el-button {
      min-width: 100px;
   }
</style>
